package com.qixiaobao.web.controller.insure;

import com.qixiaobao.common.annotation.Log;
import com.qixiaobao.common.annotation.RepeatSubmit;
import com.qixiaobao.common.core.domain.AjaxResult;
import com.qixiaobao.common.core.page.TableDataInfo;
import com.qixiaobao.common.enums.BusinessType;
import com.qixiaobao.common.exception.UtilException;
import com.qixiaobao.common.utils.StringUtils;
import com.qixiaobao.common.utils.easyExcel.EasyExcelUtil;
import com.qixiaobao.insure.domain.Insure;
import com.qixiaobao.insure.domain.SupplyInsureInfo;
import com.qixiaobao.insure.domain.dto.*;
import com.qixiaobao.insure.service.IInsureService;
import com.qixiaobao.system.domain.dto.PersonDTO;
import com.qixiaobao.web.controller.core.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Description 保单管理
 * @Author yangxm
 * @Date 2025/6/16 13:19
 */
@RestController
@RequestMapping("/insure")
public class InsureController extends BaseController {

    @Autowired
    private IInsureService insureService;

    /**
     * @Description 待生效、在保中、已失效、退保已失效 分页列表
     * @Author yangxm
     * @Date 2025/6/16 17:00
     * @param insureDTO
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @GetMapping("/list")
    public TableDataInfo list(InsureDTO insureDTO){
        insureDTO.setNoPermissionSupplyIdList(checkPermission());
        startPage();
        List<Insure> list = insureService.selectInsureList(insureDTO);
        return getDataTable(list);
    }

    /**
     * @Description 保险费总计
     * @Author yangxm
     * @Date 2025/6/17 14:23
     * @param insureDTO 
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @GetMapping("/copeInsureFeeTotal")
    public AjaxResult copeInsureFeeTotal(InsureDTO insureDTO){
        insureDTO.setNoPermissionSupplyIdList(checkPermission());
        return AjaxResult.success(insureService.copeInsureFeeTotal(insureDTO));
    }

    /**
     * @Description 投保人数总计
     * @Author yangxm
     * @Date 2025/6/17 14:23
     * @param insureDTO
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @GetMapping("/insurePersonTotal")
    public AjaxResult insurePersonTotal(InsureDTO insureDTO){
        insureDTO.setNoPermissionSupplyIdList(checkPermission());
        return AjaxResult.success(insureService.insurePersonTotal(insureDTO));
    }

    /**
     * @Description 待生效、在保中、已失效、退保已失效  导出
     * @Author yangxm
     * @Date 2025/6/17 14:10
     * @param insureDTO
     * @param response
     */
    @Log(title = "保单管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(InsureDTO insureDTO, HttpServletResponse response) {
        insureDTO.setNoPermissionSupplyIdList(checkPermission());
        insureService.export(insureDTO, response);
    }

    /**
     * @Description 人员详情
     * @Author yangxm
     * @Date 2025/6/17 15:04
     * @param personDTO
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @GetMapping("/person/list")
    public AjaxResult personList(PersonDTO personDTO){
        startPage();
        return AjaxResult.success(insureService.personList(personDTO));
    }

    /**
     * @Description 下载回单，根据筛选条件下载，供应商简称必选
     * @Author yangxm
     * @Date 2025/6/17 15:04
     * @param insureDTO
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @Log(title = "保单管理", businessType = BusinessType.DOWNLOAD_RECEIPT)
    @GetMapping("/receipt/download")
    public AjaxResult downloadReceipt(InsureDTO insureDTO){
        insureService.downloadReceipt(insureDTO);
        return AjaxResult.success();
    }

    /**
     * @Description 批量删除保单号，根据上传模板删除
     * @Author yangxm
     * @Date 2025/6/18 10:35
     * @param file
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @RepeatSubmit
    @Log(title = "保单管理", businessType = BusinessType.REMOVE_INSURE_NO_BY_TEMP)
    @PostMapping("/insureNo/removeByTemp")
    public AjaxResult removeInsureNoByTemp(@RequestParam MultipartFile file){
        byte[] bytes;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            throw new UtilException("文件格式转换异常：" + e.getMessage());
        }
        InputStream inputStream = new ByteArrayInputStream(bytes);
        //获取读取excel的数据
        List<InsureNoRemoveTempDTO> insureNoTempDtoList = EasyExcelUtil.readExcel(inputStream, InsureNoRemoveTempDTO.class);
        if (StringUtils.isEmpty(insureNoTempDtoList)) {
            throw new UtilException("导入数据不能为空");
        }
        return AjaxResult.success(insureService.removeInsureNoByTemp(insureNoTempDtoList));
    }


    /**
     * @Description 导入保单号 分析表格数据
     * @Author yangxm
     * @Date 2025/6/18 15:13
     * @param fileInfoId  文件ID
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @RepeatSubmit
    @GetMapping("/insureNo/import/analysisFile")
    public AjaxResult analysisInsureNoFile(String fileInfoId) {
        if (StringUtils.isNull(fileInfoId)){
            throw new UtilException("文件不能为空");
        }
        List<Long> noPermissionSupplyIdList = checkPermission();
        return AjaxResult.success("操作成功", insureService.analysisInsureNoFile(fileInfoId, noPermissionSupplyIdList));
    }

    /**
     * @Description 导入保单号  保存数据
     * @Author yangxm
     * @Date 2025/6/18 15:13
     * @param fileInfoId  文件ID
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @RepeatSubmit
    @Log(title = "保单管理", businessType = BusinessType.IMPORT_INSURE_NO)
    @PostMapping("/insureNo/upload")
    public AjaxResult uploadInsureNo(String fileInfoId){
        if (StringUtils.isNull(fileInfoId)){
            throw new UtilException("文件不能为空");
        }
        List<Long> noPermissionSupplyIdList = checkPermission();
        return toAjax(insureService.uploadInsureNo(fileInfoId, noPermissionSupplyIdList));
    }

    /**
     * @Description 保单号维护(天保)
     * @Author yangxm
     * @Date 2025/6/19 16:52
     * @param supplyInsureInfo
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @RepeatSubmit
    @Log(title = "保单管理", businessType = BusinessType.OPERATION_INSURE_NO)
    @PostMapping("/insureNo/operation")
    public AjaxResult operationInsureNo(@RequestBody SupplyInsureInfo supplyInsureInfo) {
        if (supplyInsureInfo.getSupplyId() == null || StringUtils.isBlank(supplyInsureInfo.getInsureNo())
                || StringUtils.isBlank(supplyInsureInfo.getDateInfo())){
            throw new UtilException("缺少参数");
        }
        return toAjax(insureService.operationInsureNo(supplyInsureInfo));
    }

    /**
     * @Description 批量删除保单文件, 根据上传模板删除
     * @Author yangxm
     * @Date 2025/6/18 14:43
     * @param file
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @RepeatSubmit
    @Log(title = "保单管理", businessType = BusinessType.REMOVE_INSURE_FILE_BY_TEMP)
    @PostMapping("/insureFile/removeByTemp")
    public AjaxResult removeInsureFileByTemp(@RequestParam MultipartFile file){
        byte[] bytes;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            throw new UtilException("文件格式转换异常：" + e.getMessage());
        }
        InputStream inputStream = new ByteArrayInputStream(bytes);
        //获取读取excel的数据
        List<InsureNoRemoveTempDTO> insureNoTempDtoList = EasyExcelUtil.readExcel(inputStream, InsureNoRemoveTempDTO.class);
        if (StringUtils.isEmpty(insureNoTempDtoList)) {
            throw new UtilException("导入数据不能为空");
        }
        return AjaxResult.success(insureService.removeInsureFileByTemp(insureNoTempDtoList));
    }


    /**
     * @Description 导入保单文件  校验保单文件名称
     * @Author yangxm
     * @Date 2025/6/19 15:59
     * @param fileNameList 
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @RepeatSubmit
    @GetMapping("/insureFile/checkUploadInsureFile")
    public AjaxResult checkUploadInsureFile(List<String> fileNameList){
        if (StringUtils.isEmpty(fileNameList)){
            throw new UtilException("导入数据不能为空");
        }
        return AjaxResult.success(insureService.checkUploadInsureFile(fileNameList));
    }

    /**
     * @Description 导入保单文件
     * @Author yangxm
     * @Date 2025/6/19 16:27
     * @param files
     * @param checkFlag 校验亚太保司保单文件的保险单号（0否1是）
     * @param coverFlag 保单是否覆盖（0否1是）
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @RepeatSubmit
    @Log(title = "保单管理", businessType = BusinessType.IMPORT_INSURE_FILE)
    @PostMapping("/insureFile/upload")
    public AjaxResult uploadInsureFile(MultipartFile[] files, String checkFlag, String coverFlag){
        if (StringUtils.isNull(files) || files.length == 0){
            throw new UtilException("文件不能为空");
        }
        return AjaxResult.success("操作成功", insureService.uploadInsureFile(files, checkFlag, coverFlag));
    }

    /**
     * @Description 定向下载模板  解析模板内容
     * @Author yangxm
     * @Date 2025/6/19 14:19
     * @param file
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @PostMapping("/customerInsDec/temp/analysisFile")
    public AjaxResult analysisQxbOrderNoFile(@RequestParam MultipartFile file){
        if (file == null){
            throw new UtilException("文件不能为空");
        }
        byte[] bytes;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            throw new UtilException("文件格式转换异常：" + e.getMessage());
        }
        InputStream inputStream = new ByteArrayInputStream(bytes);
        //获取读取excel的数据
        List<InsureQxbOrderNoTempDTO> insureQxbOrderNoTempDTOList = EasyExcelUtil.readExcel(inputStream, InsureQxbOrderNoTempDTO.class);
        if (StringUtils.isEmpty(insureQxbOrderNoTempDTOList)){
            throw new UtilException("导入数据不能为空");
        }
        return AjaxResult.success(insureService.analysisQxbOrderNoFile(insureQxbOrderNoTempDTOList));
    }

    /**
     * @Description 定向下载模板  生成凭证文件
     * @Author yangxm
     * @Date 2025/6/19 15:10
     * @param insureQxbOrderNoTempDTO
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @RepeatSubmit
    @Log(title = "保单管理", businessType = BusinessType.GENERATE_CUSTOMER_INS_DEC_BY_TEMP)
    @GetMapping("/customerInsDec/temp/generateFile")
    public AjaxResult customerInsDecByOrderNoFile(InsureQxbOrderNoTempDTO insureQxbOrderNoTempDTO){
        insureService.generateCustomerInsDec(insureQxbOrderNoTempDTO.getInsureIdList(), insureQxbOrderNoTempDTO.getSupplyShortName());
        return AjaxResult.success();
    }

    /**
     * @Description 导入凭证文件   校验凭证文件名称
     * @Author yangxm
     * @Date 2025/6/20 9:32
     * @param fileNameList 
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @RepeatSubmit
    @GetMapping("/customerInsDec/checkUploadCustomerInsDecFile")
    public AjaxResult checkUploadCustomerInsDecFile(List<String> fileNameList) {
        if (StringUtils.isEmpty(fileNameList)) {
            throw new UtilException("导入数据不能为空");
        }
        return AjaxResult.success(insureService.checkUploadCustomerInsDecFile(fileNameList));
    }

    /**
     * @Description 导入凭证文件
     * @Author yangxm
     * @Date 2025/6/20 9:55
     * @param files
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @RepeatSubmit
    @Log(title = "保单管理", businessType = BusinessType.IMPORT_CUSTOMER_INS_DEC_FILE)
    @PostMapping("/customerInsDec/upload")
    public AjaxResult uploadCustomerInsDecFile(MultipartFile[] files) {
        if (StringUtils.isNull(files) || files.length == 0) {
            throw new UtilException("文件不能为空");
        }
        return AjaxResult.success("操作成功", insureService.uploadCustomerInsDecFile(files));
    }

    /**
     * @Description 凭证下载，供应商简称必选
     * @Author yangxm
     * @Date 2025/6/20 11:42
     * @param insureDTO
     * @return com.qixiaobao.common.core.domain.AjaxResult
     *
     * 1.若页面勾选，则优先根据页面勾选的删除。
     * 2.若页面未勾选，则根据查询条件删除，供应商简称必选
     */
    @Log(title = "保单管理", businessType = BusinessType.DOWNLOAD_CUSTOMER_INS_DEC_FILE)
    @GetMapping("/customerInsDec/download")
    public AjaxResult downloadCustomerInsDecFile(InsureDTO insureDTO){
        insureDTO.setNoPermissionSupplyIdList(checkPermission());
        if (StringUtils.isEmpty(insureDTO.getSupplyIdList())){
            throw new IllegalArgumentException("缺少参数：供应商简称");
        }
        if (insureDTO.getSupplyIdList().size() > 1){
            throw new IllegalArgumentException("供应商简称只能选择一个");
        }
        insureService.downloadCustomerInsDecFile(insureDTO);
        return AjaxResult.success();
    }

    /**
     * @Description 一键生成凭证
     * @Author yangxm
     * @Date 2025/6/20 15:33
     * @param insureDTO
     * @return com.qixiaobao.common.core.domain.AjaxResult
     */
    @Log(title = "保单管理", businessType = BusinessType.GENERATE_CUSTOMER_INS_DEC)
    @GetMapping("/customerInsDec/generate")
    public AjaxResult generateCustomerInsDecFile(InsureDTO insureDTO){
        if (insureDTO == null) {
            throw new IllegalArgumentException("请求参数不能为空");
        }
        insureDTO.setNoPermissionSupplyIdList(checkPermission());
        //校验供应商简称是否为空
        if (StringUtils.isEmpty(insureDTO.getSupplyIdList())) {
            throw new IllegalArgumentException("参数：供应商简称不能为空");
        }
        //校验保单文件状态是否为“已传”
        if (!StringUtils.equals("2", insureDTO.getInsureFileStatus())) {
            throw new IllegalArgumentException("参数：保单状态必须为已传");
        }
        //校验凭证状态是否是“待传”
        if (!StringUtils.equals("1", insureDTO.getCustomerInsDecStatus())) {
            throw new IllegalArgumentException("参数：凭证状态必须为待传");
        }
        insureService.generateCustomerInsDecFile(insureDTO);
        return AjaxResult.success();
    }

    /**
     * @Description 删除  凭证/保单文件/供应商保单文件批量删除
     * @Author yangxm
     * @Date 2025/6/20 15:11
     * @param insureDTO
     * @return com.qixiaobao.common.core.domain.AjaxResult
     *
     * 1.若页面勾选，则优先根据页面勾选的删除。
     * 2.若页面未勾选，则根据查询条件删除，供应商简称必选
     */
    @RepeatSubmit
    @Log(title = "保单管理", businessType = BusinessType.REMOVE_ALL_FILE)
    @GetMapping("/removeAllFile")
    public AjaxResult removeAllFile(InsureDTO insureDTO){
        insureDTO.setNoPermissionSupplyIdList(checkPermission());
        return AjaxResult.success("操作成功", insureService.removeAllFile(insureDTO));
    }
}
